package com.tduck.cloud.history.web.scheduled;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tduck.cloud.history.web.entity.CallbackLogEntity;
import com.tduck.cloud.history.web.service.CallbackLogService;
import com.tduck.cloud.history.web.util.HttpClientUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Date: 2021/7/29 15:37
 * @Description:
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class RetryCallBackTask {

    private final CallbackLogService callbackLogService;

    // 添加定时任务
    @Scheduled(cron = "0 0/10 * * * *")
    public void doTask(){
        System.out.println("我是定时任务~");
        List<CallbackLogEntity> list = callbackLogService.list(new QueryWrapper<CallbackLogEntity>().eq("status", 0).lt("retry_times", 3));
        list.forEach(p -> {
            String url = "";
            String result = "";
            try {

                url = p.getCallbackUrl();
                result = HttpClientUtil.post(url, JSONObject.parseObject(p.getParam(),Map.class), null, "utf-8");
                JSONObject jsonObject = JSONObject.parseObject(result);
                Object success = jsonObject.get("success");
                if (success != null && Boolean.valueOf(success.toString())){
                    log.info("发送给老旧rest服务端成功,请求参数为："+ p.getParam()+";返回结果："+JSON.toJSONString(result));
                    p.setResult(result);
                    p.setStatus(1);
                    callbackLogService.updateById(p);
                } else {
                    log.info("发送给老旧rest服务端失败,请求参数为："+ p.getParam()+";返回结果："+JSON.toJSONString(result));
                    p.setResult(result);
                    p.setRetryTimes(p.getRetryTimes() != null ? p.getRetryTimes() + 1 : 0);
                    callbackLogService.updateById(p);
                }
            } catch (Exception e){
                log.error("发送给老旧rest服务端失败,请求参数为："+ p.getParam(), e);
                p.setResult(result + ";报错：" + e.getMessage());
                p.setRetryTimes(p.getRetryTimes() != null ? p.getRetryTimes() + 1 : 0);
                callbackLogService.updateById(p);
            }
        });

    }
}
